//
//  HYNewAddressViewController.m
//  Guji
//
//  Created by 华谕 on 2017/9/8.
//  Copyright © 2017年 LXF. All rights reserved.
//

#import "HYNewAddressViewController.h"
#import "CloseAreaViewController.h"
#import "AddressModel.h"

@interface HYNewAddressViewController ()<UITextFieldDelegate,UITextViewDelegate>
{
    UITextField *nameField;
    UITextField *phoneField;
    UILabel *areaLab;
    UITextView *contentView;
}
@property (nonatomic, strong)AddressModel *privesModel;
@property (nonatomic, strong)AddressModel *citysModel;
@property (nonatomic, strong)AddressModel *areasModel;


@end

@implementation HYNewAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self creatUI];
}

- (void)creatUI
{
    self.navigationItem.title = _titStr;
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = BacksColor;
    NSArray *titAry = @[@"收货人",@"联系电话",@"选择地区",@"",@"设置为默认地址"];
    NSArray *plaAry = @[@"请输入收货人姓名",@"请输入联系电话",@"请选择地区",@"",@""];
    NSArray *textAry = @[@"",@"",@"",@"请填写详细地址...",@""];
    if (_isEdit)
    {
        if ([_addmodel.isDefault integerValue] == 1)
        {
            _isOn = YES;
        }
        else
        {
            _isOn = NO;
        }
        NSString *allAddress = [NSString stringWithFormat:@"%@%@%@",_addmodel.provinceText,_addmodel.cityText,_addmodel.districtText];
        textAry = @[_addmodel.linkman,_addmodel.linkPhone,allAddress,_addmodel.detailAddress,@""];
        _privesModel = [[AddressModel alloc] init];
        _citysModel = [[AddressModel alloc] init];
        _areasModel = [[AddressModel alloc] init];

        _privesModel.ID = _addmodel.provinceId;
        _privesModel.name = _addmodel.provinceText;
        _citysModel.ID = _addmodel.cityId;
        _citysModel.name = _addmodel.cityText;
        _areasModel.ID = _addmodel.districtId;
        _areasModel.name = _addmodel.districtText;
    }
    CGFloat H = 0;
    for (int i = 0; i < titAry.count; i++)
    {
        UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, H, SCREEN_WIDTH, 50*displaywidth)];
        whiteView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:whiteView];
        UIView *lineViews = [[UIView alloc] initWithFrame:CGRectMake(0, 49*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
        lineViews.backgroundColor = LinesColor;
        [whiteView addSubview:lineViews];
        CGFloat width = 70*displaywidth;
        if (i == titAry.count-1)
        {
            width = SCREEN_WIDTH-130*displaywidth;
        }
        if (i != 3)
        {
            UILabel *leftLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 5*displaywidth, width, 40*displaywidth) Font:14.0 Text:titAry[i] Color:RGB(77, 77, 77)];
            [whiteView addSubview:leftLab];
             H += 50*displaywidth;
            
        }
        
        
        if (i == 0 || i == 1)
        {
            UITextField *textfield = [ZCControl createTextFieldWithFrame:CGRectMake(85*displaywidth, 5*displayheight, SCREEN_WIDTH-105*displaywidth, 40*displayheight) placeholder:plaAry[i] passWord:NO leftImageView:nil rightImageView:nil Font:14.0];
            [textfield setValue:RGB(204, 204, 204) forKeyPath:@"_placeholderLabel.textColor"];
            textfield.textColor = RGB(77, 77, 77);
            textfield.delegate = self;
            textfield.clearButtonMode = UITextFieldViewModeWhileEditing;
            textfield.textAlignment = NSTextAlignmentRight;
            textfield.text = textAry[i];
            [whiteView addSubview:textfield];
            if (i == 0)
            {
                nameField = textfield;
            }
            else
            {
                textfield.keyboardType = UIKeyboardTypeNumberPad;
                phoneField = textfield;
            }
            
        }
        if (i == 2)
        {
            UILabel *rightLab = [ZCControl createLabelWithFrame:CGRectMake(85*displaywidth, 5*displaywidth, SCREEN_WIDTH-120*displaywidth, 40*displaywidth) Font:14.0 Text:textAry[i] Color:RGB(77, 77, 77)];
            rightLab.textAlignment = NSTextAlignmentRight;
            [whiteView addSubview:rightLab];
            UIImageView *rightImg = [ZCControl createImageViewWithFrame:CGRectMake(SCREEN_WIDTH-30*displaywidth, 17.5*displaywidth, 15*displaywidth, 15*displaywidth) ImageName:@"nextimg"];
            rightImg.contentMode = UIViewContentModeScaleAspectFit;
            [whiteView addSubview:rightImg];
            UIButton *button = [ZCControl createButtonWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50*displaywidth) ImageName:nil Target:self Action:@selector(choseAction:) Title:nil Font:12.0];
            button.backgroundColor = [UIColor clearColor];
            button.tag = i;
            [whiteView addSubview:button];
           
            areaLab = rightLab;
            
        }
        if (i == 3)
        {
            whiteView.frame = CGRectMake(0, H, SCREEN_WIDTH, 90*displaywidth);
            H += 100*displaywidth;
            UITextView *textview = [[UITextView alloc] initWithFrame:CGRectMake(15*displaywidth, 5*displaywidth, SCREEN_WIDTH-30*displaywidth, 80*displaywidth)];
            textview.delegate = self;
            textview.text = textAry[i];
            textview.textColor = RGB(77, 77, 77);
            if ([textAry[i] isEqualToString:@"请填写详细地址..."])
            {
                textview.textColor = RGB(204, 204, 204);
            }
            [whiteView addSubview:textview];
            contentView = textview;
            lineViews.hidden = YES;
        }
        if ( i == 4)
        {
            UISwitch *oneSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-60*displaywidth, 11*displaywidth, 60*displaywidth, 20*displaywidth)];
            oneSwitch.alpha = 1;
            oneSwitch.backgroundColor = RGB(204, 204, 204);
            oneSwitch.transform = CGAffineTransformMakeScale(0.8, 0.8);
            oneSwitch.onTintColor = ThemeColor;
            // 设置关闭状态的颜色
            oneSwitch.tintColor = RGB(204, 204, 204);
            // 设置开关上左右滑动的小圆点的颜色
            oneSwitch.thumbTintColor = [UIColor whiteColor];
            // 设置初始状态 直接设置为on，你不回观察到它的变化
            oneSwitch.on = _isOn;
            // 设置初始状态，与上面的不同是当你看到这个控件的时候再开始设置为on，你会观察到他的变化
            [oneSwitch setOn:_isOn animated:YES];
            [oneSwitch addTarget:self action:@selector(oneSwitchValueChanged:) forControlEvents:UIControlEventValueChanged];
            [whiteView addSubview:oneSwitch];
            oneSwitch.layer.cornerRadius = oneSwitch.bounds.size.height/2.0;
            lineViews.hidden = YES;

        }
    }
   
    
    UIButton *soureBtn = [ZCControl createButtonWithFrame:CGRectMake(60*displaywidth , H + 40*displaywidth, SCREEN_WIDTH-120*displaywidth, 40*displaywidth) ImageName:nil Target:self Action:@selector(soureBtnAction) Title:@"确认" Font:15.0];
    [soureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    soureBtn.backgroundColor = ThemeColor;
    [soureBtn.layer setMasksToBounds:YES];
    [soureBtn.layer setCornerRadius:5*displaywidth];
    [self.view addSubview:soureBtn];

}




//选择
- (void)choseAction:(UIButton *)btn
{
    [self.view endEditing:YES];
    CloseAreaViewController *vc = [[CloseAreaViewController alloc] init];
    WEAKSELF;
    vc.chooseblock = ^(AddressModel *priveModel, AddressModel *cityModel, AddressModel *areaModel)
    {
        weakSelf.privesModel = priveModel;
        weakSelf.citysModel = cityModel;
        weakSelf.areasModel = areaModel;
        dispatch_async(dispatch_get_main_queue(), ^{
            areaLab.text = [NSString stringWithFormat:@"%@-%@-%@",priveModel.name,cityModel.name,areaModel.name];

        });
    };
    [self.navigationController pushViewController:vc animated:YES];
    
}

//确定
- (void)soureBtnAction
{
    [self.view endEditing:YES];
    WEAKSELF;
    if (nameField.text.length < 1)
    {
        [LTools showMBProgressWithText:@"请输入收货人姓名" addToView:self.view];
        return;
    }
    if (phoneField.text.length != 11)
    {
        [LTools showMBProgressWithText:@"请输入联系电话" addToView:self.view];
        return;
    }
    if ([areaLab.text isEqualToString:@""])
    {
        [LTools showMBProgressWithText:@"请选择地区" addToView:self.view];
        return;
    }
    if ([contentView.text isEqualToString:@"请填写详细地址..."])
    {
        [LTools showMBProgressWithText:@"请填写详细地址" addToView:self.view];
        return;
    }
    NSString *isonstr = @"0";
    if (_isOn)
    {
        isonstr = @"1";
    }
    NSString *idStr = @"";
    if (_isEdit)
    {
        idStr = _addmodel.ID;
    }
    NSDictionary *dic = @{@"cityId":_citysModel.ID,
                          @"cityText":_citysModel.name,
                          @"detailAddress":contentView.text,
                          @"districtId":_areasModel.ID,
                          @"districtText":_areasModel.name,
                          @"isDefault":isonstr,
                          @"linkPhone":phoneField.text,
                          @"linkman":nameField.text,
                          @"id":idStr,
                          @"provinceId":_privesModel.ID,
                          @"provinceText":_privesModel.name
                          };
    [HYBaseHandler requestSaveAddressParmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            [LTools showMBProgressWithText:@"操作成功" addToView:sharedDelegate.window];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {

    }];
}


- (void)oneSwitchValueChanged:(UISwitch *) sender {
    NSLog(@"%@", sender.isOn ? @"ON" : @"OFF");
    _isOn = sender.isOn;
    [self.view endEditing:YES];

}




- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

//开始编辑
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    textView.textColor = RGB(77, 77, 77);
    if ([textView.text isEqualToString:@"请填写详细地址..."])
    {
        textView.text= @"";
    }
}
//结束编辑
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@""])
    {
        textView.text= @"请填写详细地址...";
        textView.textColor = RGB(204, 204, 204);
    }
    
}
//-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
//{
//    _strLengthLab.text = [NSString stringWithFormat:@"%ld/300",textView.text.length];
//    NSInteger  charactersAfterChange = textView.text.length + text.length - range.length;
//    if (charactersAfterChange >= 300)
//    {
//        return NO;
//    }
//    //删除
//    if ([text isEqualToString:@""]) {
//        return YES;
//    }
//    if ([text isEqualToString:@"\n"]) {
//        [textView resignFirstResponder];
//        return NO;
//    }
//
//    return YES;
//}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
